/* Parse a configuration file into a struct using X-Macros */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include "utils.h"
#include "version.h"

int main(int argc, char *argv[])
{
	char portbuf[128];
	char bandbuf[128];
	char cmdbuf[128];

	if (CheckCmdLine(argc, argv, "h") || argc < 2)
	{
		printf("Uages:%s [-h] --port:<dev/ttySx> --band:<9600> --devid:<1> --fcode:<0x03> --reg:<0x0000> --regn:<1> [--regv:<FFFF>]\r\n",argv[0]);
		printf("\t\t--port:<dev/ttySx>\t\tRS485's device name,default is /dev/ttyS0.\r\n");
		printf("\t\t--band:<9600>\t\tBandrate for rs485\r\n");
		printf("\t\t--cmd:<>\t\tcommand by hex string\r\n");
		return 0;
	}

	if (!GetCmdParamValue(argc, argv, "port", portbuf))
	{
		strcpy(portbuf,"/dev/ttyS0");
	}

	if (!GetCmdParamValue(argc, argv, "band", bandbuf))
	{
		strcpy(bandbuf,"9600");
	}

	if (!GetCmdParamValue(argc, argv, "cmd", cmdbuf))
	{
		printf("Uages:%s [-h] --port:<dev/ttySx> --band:<9600> --devid:<1> --fcode:<0x03> --reg:<0x0000> --regn:<1> [--regv:<FFFF>]\r\n",argv[0]);
		printf("\t\t--port:<dev/ttySx>\t\tRS485's device name,default is /dev/ttyS0.\r\n");
		printf("\t\t--band:<9600>\t\tBandrate for rs485\r\n");
		printf("\t\t--cmd:<>\t\tcommand by hex string\r\n");
		return 0;
	}

    int ret;
	int band = StrToInt(bandbuf);
	int uartfd = com_open(portbuf,O_RDWR | O_NOCTTY | O_NONBLOCK);

	if (uartfd <= 0)
	{
		printf("open uart %s error:%s\r\n", portbuf, strerror(errno));
		return -1;
	}

	char cmd[256];
	int cmdlen = sizeof(cmd);

	HexDecode(cmdbuf,strlen(cmdbuf),cmd,&cmdlen);
	if(cmdlen>0){
		write(uartfd,cmd,cmdlen);
	}else{
		printf("Hex string to cmd error.\r\n");
	}
	close(uartfd);

	return 0;
}
